package root.electronclass.electronclass.home.widget;

import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import root.electronclass.electronclass.MainActivity;
import root.electronclass.electronclass.R;
import root.electronclass.electronclass.common.base.BasicAdapter;
import root.electronclass.electronclass.common.base.BindingHolder;
import root.electronclass.electronclass.common.util.DateHelper;
import root.electronclass.electronclass.databinding.HomeCourseInfoBinding;
import root.electronclass.electronclass.databinding.HomeItemCourseBinding;
import root.electronclass.electronclass.grade.curriculum.ClassCurriculumFragment;
import root.electronclass.electronclass.mvp.GlobalParameter;
import root.electronclass.electronclass.mvp.base.BaseResponse;
import root.electronclass.electronclass.mvp.entity.HomeCourseInfoH;
import root.electronclass.electronclass.mvp.rest.RestManager;

public class HomeCourseView {
    private static final String TAG = "HomeCourseView";

    private final Context context;
    private final HomeCourseInfoBinding binding;
    private final PagerSnapHelper pagerSnapHelper;

    private final Handler handler = new Handler(Looper.getMainLooper());


    public HomeCourseView(Context context, ViewGroup view) {
        this.binding = HomeCourseInfoBinding.bind(view);
        this.context = context;
        pagerSnapHelper = new PagerSnapHelper();
        init();
        refreshSelf();
    }

    private final BasicAdapter<HomeCourseInfoH, HomeItemCourseBinding> adapter = new BasicAdapter<HomeCourseInfoH, HomeItemCourseBinding>() {
        @Override
        public void onBindViewHolder(@NonNull BindingHolder<HomeItemCourseBinding> holder, @Nullable HomeCourseInfoH item) {
            if (item == null || TextUtils.isEmpty(item.getSubject())) {
                holder.getBinding().getRoot().setVisibility(View.INVISIBLE);
            } else {
                holder.getBinding().getRoot().setVisibility(View.VISIBLE);
                holder.getBinding().tvName.setText(item.getSubject());
                holder.getBinding().tvDate.setText(item.getStartTime() + "～" + item.getEndTime());
                holder.getBinding().tvSignStudent.setText(item.getSignedStudentCount() + "");
                holder.getBinding().tvLateStudent.setText(item.getLateStudentCount() + "");
                if (item.getState() == 0) {
                    holder.getBinding().tvState.setText("已结束");
                    holder.getBinding().tvState.setEnabled(false);
                    holder.getBinding().tvState.setSelected(false);
                } else if (item.getState() == 1) {
                    holder.getBinding().tvState.setText("进行中");
                    holder.getBinding().tvState.setEnabled(true);
                    holder.getBinding().tvState.setSelected(false);
                } else if (item.getState() == 2) {
                    holder.getBinding().tvState.setText("下节预告");
                    holder.getBinding().tvState.setEnabled(true);
                    holder.getBinding().tvState.setSelected(true);
                } else {
                    holder.getBinding().tvState.setText("等待中");
                    holder.getBinding().tvState.setEnabled(false);
                    holder.getBinding().tvState.setSelected(false);
                }
                holder.getBinding().getRoot().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setCurrentItem(holder.getBindingAdapterPosition());
                    }
                });
            }

//            if (item.getState() == 1) {
//                holder.getBinding().tvName.setTextColor(Color.parseColor("#FFFFFF"));
//                holder.getBinding().tvDate.setTextColor(Color.parseColor("#FFFFFF"));
//                holder.getBinding().tvState.setTextColor(Color.parseColor("#FFFFFF"));
//            } else {
//                holder.getBinding().tvName.setTextColor(Color.parseColor("#071129"));
//                holder.getBinding().tvDate.setTextColor(Color.parseColor("#071129"));
//                holder.getBinding().tvState.setTextColor(Color.parseColor("#071129"));
//            }
        }

        @Override
        public void onBindViewHolder(@NonNull BindingHolder<HomeItemCourseBinding> holder, int position) {
            super.onBindViewHolder(holder, position);

        }
    };

    private void init() {
        binding.rcvCourseList.setVisibility(View.GONE);
//        binding.rcvCourseList.setOffscreenPageLimit(3);

        Resources resources = binding.rcvCourseList.getContext().getResources();
        int pageMarginPx = resources.getDimensionPixelOffset(R.dimen.pageMargin);
        int pagerWidth = resources.getDimensionPixelOffset(R.dimen.pagerWidth);
        int screenWidth = 760;
        int offsetPx = screenWidth - pagerWidth;

//        binding.rcvCourseList.setPageTransformer(new CardPageTransformer());
//        binding.rcvCourseList.setClipToPadding(false);
//        binding.rcvCourseList.setClipChildren(false);
//        binding.rcvCourseList.setPadding(offsetPx / 2, 0, offsetPx / 2, 0);
//        binding.rcvCourseList.setPageMargin(pageMarginPx);
        binding.rcvCourseList.setLayoutManager(new EnhancedScaleLayoutManager(context));
//        binding.rcvCourseList.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false));
        pagerSnapHelper.attachToRecyclerView(binding.rcvCourseList);
        binding.rcvCourseList.addItemDecoration(new PageMarginItemDecoration(pageMarginPx));
        binding.rcvCourseList.setAdapter(adapter);
        binding.rcvCourseList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    View snapView = pagerSnapHelper.findSnapView(recyclerView.getLayoutManager());
                    if (snapView != null) {
                        int position = recyclerView.getChildAdapterPosition(snapView);
                        onPageChanged(position);
                    }

                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                recyclerView.post(() -> {
                    if (recyclerView.getLayoutManager() != null) {
                        recyclerView.getLayoutManager().requestLayout();
                    }
                });
            }
        });

        binding.tvMore.setOnClickListener(v -> {
            MainActivity fragmentActivity = ((MainActivity) context);
            Bundle bundle = new Bundle();
            bundle.putSerializable("TARGET_CLASS", ClassCurriculumFragment.class);
            fragmentActivity.selectPage(MainActivity.Page.CLASS, bundle);
        });
        request();
    }

    private void setCurrentItem(int position) {
        int recyclerViewWidth = binding.rcvCourseList.getWidth();
        int offset = (recyclerViewWidth - (308 + 20)) / 2;
        if (binding.rcvCourseList.getLayoutManager() != null) {
            ((LinearLayoutManager) binding.rcvCourseList.getLayoutManager()).scrollToPositionWithOffset(position, offset);
        }
    }

    private int lastPosition = -1;
    private void onPageChanged(int position) {
        if (lastPosition != position) {
            lastPosition = position;
            setCurrentItem(position);
        }
    }

    private List<HomeCourseInfoH> dataList;

    public void request() {
        long id = GlobalParameter.getEcardInfo().getClassId();
        RestManager.getInstance().initRest().homeCourse(String.valueOf(id)).enqueue(new Callback<>() {
            @Override
            public void onResponse(@NonNull Call<BaseResponse<List<HomeCourseInfoH>>> call, @NonNull Response<BaseResponse<List<HomeCourseInfoH>>> response) {
                if (response.isSuccessful()) {
                    binding.rcvCourseList.setVisibility(View.VISIBLE);
                    dataList = response.body().getRows();
                    int index = resetList();
                    dataList.add(0, new HomeCourseInfoH());
                    dataList.add(new HomeCourseInfoH());
                    adapter.replaceAll(dataList);
                    Looper.myQueue().addIdleHandler(() -> {
                        if (index != -1) {
                            setCurrentItem(index);
                        } else {
                            setCurrentItem(1);
                        }
                        return false;
                    });
                    refreshSelf();
                }
            }

            @Override
            public void onFailure(@NonNull Call<BaseResponse<List<HomeCourseInfoH>>> call, @NonNull Throwable t) {

            }
        });
    }


    private void refreshSelf() {
        handler.postDelayed(refreshRunnable, 4000);
    }


    private int resetList() {
        if (dataList != null) {
            boolean isJust = true;
            int selectIndex = -1;
            for (int i = 1; i < dataList.size() - 1; i++) {
                if (DateHelper.isNowAfterTime(dataList.get(i).getEndTime())) {
                    dataList.get(i).setState(0);
                } else if (DateHelper.isNowBetweenTime(dataList.get(i).getStartTime(), dataList.get(i).getEndTime())) {
                    dataList.get(i).setState(1);
                    selectIndex = i;
                } else {
                    if (isJust) {
                        dataList.get(i).setState(2);
                        if (selectIndex == -1) {
                            selectIndex = i;
                        }
                        isJust = false;
                    } else {
                        dataList.get(i).setState(3);
                    }
                }
            }
            return selectIndex;
        } else {
            return -1;
        }


    }

    public void refresh() {
        request();
    }

    private final Runnable refreshRunnable = new Runnable() {
        @Override
        public void run() {
            if (isDestroy) {
                return;
            }
            if (dataList != null) {
                int index = resetList();
                adapter.notifyDataSetChanged();
                if (index != -1) {
                    setCurrentItem(index);
                }
            }
            handler.postDelayed(refreshRunnable, 10000);
        }
    };

    private boolean isDestroy = false;

    public void destroy() {
        isDestroy = true;
    }

}
